package tokenmem

import (
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"sync"
	"gitee.com/zxs-micro/zxs-micro-auth/grpc/authserver/model"
	"gitee.com/zxs-micro/zxs-micro-common/utils/commonredis"
)

type RedisTokenMem struct {
	l        sync.Mutex
	connAddr string
	connPwd  string
	pool     *redis.Pool
}

var r *RedisTokenMem

func NewRedisTokenMem(node, pwd string) {
	if r != nil {
		return
	}
	r = new(RedisTokenMem)
	r.connAddr = node
	r.connPwd = pwd
	if pwd == "" {
		commonredis.InitRedisConn(node)
	} else {
		commonredis.InitRedisConnWithPwd(node, pwd)
	}
	r.pool = commonredis.RdPool
}

func (r *RedisTokenMem) MemType() string {
	return "redis"
}

func (r *RedisTokenMem) GetToken(token string) (*model.TokenModel, error) {
	result := new(model.TokenModel)
	c := r.pool.Get()
	defer c.Close()
	rep, err := c.Do("GET", token)
	if err != nil {
		return result, err
	}
	bs, err := redis.Bytes(rep, err)
	if err != nil {
		return result, err
	}
	err = json.Unmarshal(bs, &result)
	return result, err
}

func (r *RedisTokenMem) AddToken(token string, t *model.TokenModel) error {
	bs, _ := json.Marshal(t)
	c := r.pool.Get()
	defer c.Close()
	_, err := c.Do("SET", token, bs)
	return err
}

func (r *RedisTokenMem) DeleteToken(token string) error {
	c := r.pool.Get()
	defer c.Close()
	_, err := c.Do("DEL", token)
	return err
}
